<template>
  <div class="page-dialogAd">
    <filter-view @update-list="() => getDialogAdList()" />
    <a-table
      id="sortTable"
      :row-selection="{
        selectedRowKeys: statusState.selectedRowKeys,
        checkStrictly: false,
        onChange: onSelectChange
      }"
      :pagination="false"
      :expandRowByClick="false"
      row-key="id"
      :columns="columns"
      :data-source="state.dialogAdList"
      :loading="state.loading"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-else-if="column.key === 'img_url'">
          <a-image
            width="37.6px"
            height="39.85px"
            class="w-[-webkit-fill-available] object-contain"
            :src="getIcon(record)"
            :fallback="defaultImage"
          />
        </template>
        <template v-else-if="column.key === 'name'">
          <a-tooltip placement="top" color="#fff">
            <template #title>
              {{ record.name }}
            </template>
            <div class="ellipsis-text">
              {{ record.name || '-' }}
            </div>
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'jump_addr'">
          <a-tooltip placement="top" color="#fff">
            <template #title>
              {{ record.jump_addr }}
            </template>
            <div class="ellipsis-multipleText">
              {{ record.jump_addr || '-' }}
            </div>
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'created_at'">
          {{ formatToDateTime(record.created_at * 1000) }}
        </template>
        <template v-else-if="column.key === 'status'">
          <span>
            <a-switch
              :checked="record.status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="updateDialogAd(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="basicColor" @click="deleteDialogAd(record)"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <a-pagination
      @change="handlePaginationChange"
      show-size-changer
      :defaultPageSize="10"
      :pageSizeOptions="['10', '20', '50', '100']"
      :show-total="(total:number)=>`共${total}条`"
      :total="queryState.total"
    />
    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该广告吗</span>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, computed, inject } from 'vue'
import { message } from 'ant-design-vue'
import FilterView from './components/FilterView.vue'
import { column } from './dataSource'
import Sortable from 'sortablejs'
import type { DialogListData } from '@/types/advertising/dialogAd'
import ModalView from '@/components/components/modal/ModalView.vue'
import { dialogAdState, statusState } from './state'
import { useRouter } from 'vue-router'
import apis from '@/apis'
import { formatToDateTime } from '@/utils/format'
import { storage } from '@/utils/storage'
import defaultImage from '@/assets/icon/defaultImage.png'
const {
  advertising: { list, update_status, delete_ad, advertising_order }
} = apis
const imageDomain = inject('imageDomain') as any
const baseUrl = computed(() => {
  return imageDomain?.adv_cover || window.location.origin + '/'
})
const router = useRouter()
const columns = ref(column)
const deleteVisible = ref(false)
const state = reactive<{ loading: boolean; dialogAdList: DialogListData[] }>({
  loading: false,
  dialogAdList: [] as DialogListData[]
})
type Key = string
const deleteId = ref()
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getDialogAdList()
}

//根据类型获取图片
const getIcon = computed(() => (item: DialogListData) => {
  if (item.img_type === 1) return baseUrl.value + item.img_url
  return item.img_url
})
//获取弹窗广告列表接口
const getDialogAdList = () => {
  state.loading = true
  const params = {
    library_id: storage.get('libraryId'),
    adv_type: 2,
    sort: '',
    order: 0,
    ...dialogAdState,
    ...queryState
  }
  if (!params.id) params.id = undefined
  // 更新列表接口
  list(params)
    .then((res: any) => {
      console.log(res, 'res')
      state.dialogAdList = res?.list ?? []
      queryState.total = res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.list ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getDialogAdList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
//删除
const deleteDialogAd = (item: DialogListData) => {
  console.log('item: ', item)
  deleteId.value = item.id
  deleteVisible.value = true
}
//编辑
const updateDialogAd = (item: DialogListData) => {
  console.log('item: ', item)
  router.push({ name: 'EditDialogAd', query: { id: item.id } })
}
//修改状态
const editStatus = (checked: number, row: DialogListData) => {
  console.log('row: ', checked, row.id)
  const data = {
    status: checked,
    id: row.id
  }
  console.log('data: ', data.id)
  update_status(data)
    .then(() => {
      message.success(checked === 1 ? '启用成功' : '禁用成功')
      getDialogAdList()
    })
    .catch(() => {
      getDialogAdList()
    })
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  delete_ad({ id: deleteId.value }).then((res: any) => {
    message.success('删除成功')
    deleteVisible.value = value
    getDialogAdList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
//调用排序接口
const sortFunc = (item: any) => {
  advertising_order({
    ...item
  }).then(() => {
    message.success('排序成功')
    getDialogAdList()
  })
}
//初始化表格拖动
const initSortable = () => {
  const el = document.querySelector('#sortTable tbody') as HTMLElement
  console.log({ el })
  new Sortable(el, {
    handle: '.ant-table-row',
    animation: 150,
    ghostClass: 'blue-background-class',
    forceFallback: true,
    sort: true,
    // async
    onEnd(item) {
      console.log({ item })
      if (item.newIndex === item.oldIndex) return
      const startIndex = (item.oldIndex as number) - 1
      const endIndex = (item.newIndex as number) - 1
      const { id } = state.dialogAdList[startIndex]
      const { order } = state.dialogAdList[endIndex]
      sortFunc({ id, order })
    }
  })
}
onMounted(() => {
  getDialogAdList()
  initSortable()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.page-dialogAd {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }
  :deep(.ellipsis-multipleText) {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    cursor: pointer;
  }
  .basicColor {
    color: @basicColor;
  }
}
</style>
